package com.kgc.scd.controller;

import com.kgc.scd.contant.WechatPayConstant;
import com.kgc.scd.service.WechatPayService;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Created On : 2022/5/31.
 * <p>
 * Author     : 98730
 * <p>
 * Description: 微信支付统一操作入口
 */
@Slf4j
@RestController
@Api(tags = "微信支付操作入口")
public class WechatPayController {

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * @author : 98730
     * @date   : 2022/5/31
     * @param  : []
     * @return : com.kgc.scd.util.RequestResult<java.util.Map<java.lang.String,java.lang.String>>
     * @description : 请求微信官方，统一下单，返回支付链接
     */
    @PostMapping("/unifiedOrder")
    @ApiOperation(value = "生成微信支付接口",notes = "请求微信官方，统一下单，返回支付结果")
    public RequestResult<Map<String, String>> wechatPayUnifiedOrder(@RequestParam String orderId) throws Exception {

        // 调用业务接口，生成请求微信官方支付系统，统一下预支付订单完整接口参数(格式是xml字符串)
        String unifiedOrderParamsXml = wechatPayService.wechatUnifiedOrderParamsXml("123", 1, orderId,orderId);

        log.info("------ 1 请求微信官方，进行统一下单，接口参数：{} ------", unifiedOrderParamsXml);

        // 定义统一返回的结果集
        Map<String, String> resultMap = wechatPayService.wechatPayUnifiedOrder(unifiedOrderParamsXml);

        // 请求微信官方统一下单，下预支付订单
        Map<String,String> unifiedOrderResultMap = wechatPayService.wechatPayUnifiedOrder(unifiedOrderParamsXml);

        // 解析统一下预支付订单结果，获取支付的二维码链接，用于生成二维码，然后提供给用户进行扫码支付
        if (WechatPayConstant.WECHAT_PAY_SUCCESS.equals(unifiedOrderResultMap.get("return_code")) &&
            WechatPayConstant.WECHAT_PAY_SUCCESS.equals(unifiedOrderResultMap.get("result_code"))){
            // 交易类型
            resultMap.put("trade_type", unifiedOrderResultMap.get("trade_type"));

            // 预支付交易会话标识
            resultMap.put("prepay_id", unifiedOrderResultMap.get("prepay_id"));

            // 二维码链接
            resultMap.put("code_url", unifiedOrderResultMap.get("code_url"));

            // 返回成功下单结果
            return ResultBuildUtil.success(resultMap);
        }

        // 返回失败下单结果
        return ResultBuildUtil.fail(unifiedOrderResultMap.get("return_code"),unifiedOrderResultMap.get("return_msg"));
    }

    /**
     * @author : 98730
     * @date   : 2022/5/31
     * @param  : [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return : void
     * @description : 接收微信支付结果异步回调
     */
    @RequestMapping("/wxpayResultBack")
    @ApiOperation(value = "微信统一下单异步回调接口",notes = "订单确认接口")
    public void wechatPayResultBack(HttpServletRequest request, HttpServletResponse response){

        try(InputStream inputStream = request.getInputStream()) {

            // 读取支付回调结果
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 逐行读取
            String readLine;
            // 定义返回的动态字符串对象
            StringBuilder wxPayResultBackXml = new StringBuilder();

            // 循环读取
            while ((readLine = bufferedReader.readLine()) != null){
                wxPayResultBackXml.append(readLine);
            }

            log.info("------ 2 微信官方，支付结果回调，回调结果：{} ------",wxPayResultBackXml);

            // 解析异步回调支付结果，并获取同步返回给微信官方的响应
            String wxPayResultBackResponseXml = wechatPayService.wechatPayNotifyResultResolve(wxPayResultBackXml.toString());

            // 同步返回响应给微信官方
            PrintWriter out = response.getWriter();
            out.write(wxPayResultBackResponseXml);
            out.flush();
            out.close();

            log.info("------ 3 微信官方，支付结果回调，响应结果：{} ------",wxPayResultBackResponseXml);


        } catch (Exception ex){

            log.error("------ 4 微信官方，支付结果回调，异常：{} ------",ex.getMessage());
        }
    }

}
